package com.example.studentmanagersystem;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.fs.db.DBMethod;
import com.fs.po.DBUser;
import com.fs.po.UserLogin;
import com.fs.utils.LoginHttpUtil;

/**
 * @version 1
 * @author chenwenfei
 * data 2015-11-11
 *
 */
public class MainActivity extends Activity implements OnClickListener {

	public static final int TYPE_ADMIN=0;
	public static final int TYPE_STU=1;
	public static final int TYPE_TEC=2;
	
	private static final String m[] = { "管理员", "学生", "老师" };
	private Spinner spinner;
	private ArrayAdapter<String> adapter;
	private TextView spinnerTextview,newUserRegist;
	private Button loginSubmitBtn,actionBack,actionMenu;
	private EditText usernameET,passwordET;
	private CheckBox autoLogin,rememberPsw;

	public static String username,password;
	public static int _id;
	int spinnerSelected;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main_login);
		
		//
		this.spinnerSelectAction();
		
		//initialize variable
		this.init();
		
		//auto login
		this.autoRemListener();
		
	}

	/**
	 * initialize variable
	 */
	private void init() {
		this.usernameET=(EditText) this.findViewById(R.id.index_login_input_username);
		this.passwordET=(EditText) this.findViewById(R.id.index_login_input_password);
		this.newUserRegist=(TextView) this.findViewById(R.id.index_login_regist_newuser);
		this.loginSubmitBtn = (Button) this.findViewById(R.id.index_login_submitButton);
		
		this.actionBack=(Button) this.findViewById(R.id.index_action_backButton);
		this.actionMenu=(Button) this.findViewById(R.id.index_action_menu);
		
		this.rememberPsw=(CheckBox) this.findViewById(R.id.index_Login_rememberPassword);
		this.autoLogin=(CheckBox) this.findViewById(R.id.index_Login_autologin);
		
		this.newUserRegist.setOnClickListener(this);
		this.loginSubmitBtn.setOnClickListener(this);
		this.actionBack.setOnClickListener(this);
		this.actionMenu.setOnClickListener(this);
	}

	/**
	 * Listener:login regist back menu
	 */
	@Override
	public void onClick(View v) {
		Intent intent;
		int id=v.getId();
		if (id == R.id.index_login_submitButton) {//login button
			this.userLogin();//user login
		}else if(id==R.id.index_login_regist_newuser){//regist button
			intent = new Intent(this, RegistActivity.class);
			this.startActivity(intent);
		}else if(id==R.id.index_action_backButton){//back button
			exit();
		}else if(id==R.id.index_action_menu){//menu button
			PopupMenuUtil popupMenuUtil=new PopupMenuUtil(v, MainActivity.this);
			popupMenuUtil.actionBackListener();
		}
	}
	
	
	/**
	 * remember password auto login
	 */
	
	boolean isCheck=false;
	private void autoRemListener() {

		this.rememberPsw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				 
				if(isChecked){
					
					isCheck=isChecked;
					
//					remenberPsw();
					System.out.println("CHECKBOX_被选择"+isCheck);
					
				}
				
			}
		});
		
		this.autoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				
				
				
			}
		});

	}

	
	
	/**
	 * select the login identity
	 */
	private void spinnerSelectAction() {

		this.spinnerTextview = (TextView) this.findViewById(R.id.index_login_userText);
		this.spinner = (Spinner) this.findViewById(R.id.index_login_bodySelect);
		adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice, m);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
				MainActivity.this.spinnerTextview.setText(m[arg2]);
				MainActivity.this.spinnerSelected=arg2;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}

		});

	}
	
	/**
	 * login
	 */
	private void userLogin() {
		LoginHttpUtil myHttpUtil=new LoginHttpUtil(this,mHandler);
		this.username=this.usernameET.getText().toString().trim();//get username
		this.password=this.passwordET.getText().toString().trim();//get password
		
		Intent intent;
		if(this.spinnerSelected==TYPE_ADMIN){//admin login
			
			String action="login";
			myHttpUtil.mainActivityLoginSubmit(action,"admin_name", "admin_passwodr", new UserLogin(username, password),URL.ADMIN_URL,TYPE_ADMIN);
			
		
		}else if(this.spinnerSelected==TYPE_STU){//student login
			
			String action="login";
			myHttpUtil.mainActivityLoginSubmit(action,"stu_name", "stu_passwodr", new UserLogin(username, password),URL.STU_URL,TYPE_STU);
		
		}else if(this.spinnerSelected==TYPE_TEC){//teacher login
			
			String action="login";
			myHttpUtil.mainActivityLoginSubmit(action,"tec_name", "tec_passwodr", new UserLogin(username, password),URL.TEC_URL,TYPE_TEC);
		
		}
	}
	
	/**
	 * if login success,destroy MainActivity
	 */
	int isSuccess;
	
	Handler mHandler = new Handler() {  
		  
        @Override  
        public void handleMessage(Message msg) {  
            super.handleMessage(msg);  
            isSuccess=msg.arg1;
            if(isSuccess==1){
            	
            	if(isCheck){
            		
            		remenberPsw();//remember password
            		
            	}
            	
            	MainActivity.this.finish();
            }
            
            isExit = false; 
        }  
  
    }; 
	
    /**
	 * exit
	 */
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		
		 if (keyCode == KeyEvent.KEYCODE_BACK) {  
			 
	            exit(); 
	            
	            return true;  
	            
	        } else {  
	        	
	            return super.onKeyDown(keyCode, event);  
	        	 
	        }  
	}

	boolean isExit=false;
	private void exit() {
		 
		if (!isExit) {  
            isExit = true;  
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();  
            
            mHandler.sendEmptyMessageDelayed(0, 2000);  
            
        } else {  
        	
            Intent intent = new Intent(Intent.ACTION_MAIN);  
            intent.addCategory(Intent.CATEGORY_HOME);  
            startActivity(intent);  
        }  
		
	}
	
	
	/**
	 * remember method
	 */
	
	private void remenberPsw() {

		System.out.println("DBUTILS:");
		
		DBMethod dbMethod=new DBMethod(this, new DBUser(username, password));
		dbMethod.createDB();
		dbMethod.createTable();
		dbMethod.insert();
		
	}
	
}
